package org.aom.util;

import java.util.Random;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;

/**
 * 通用工具类
 * 
 * @author Saya
 */
public class Util {
	private Util() {
	}
	
	/**
	 * 获取数字随机数
	 * 
	 * @param size
	 *            随机数个数
	 * @return 指定个数的数字随机数的字符串
	 */
	public static String getRandom(int size) {
		Random random = new Random();
		StringBuilder sb = new StringBuilder(size);
		for (int i = 0; i < size; i++) {
			sb.append(random.nextInt(9));
		}
		return sb.toString();
	}

	/**
	 * 创建指定EL方法表达式的MethodExpressionActionListener
	 * 
	 * @param context
	 *            FacesContext
	 * @param expression
	 *            EL方法表达式
	 * @return MethodExpressionActionListener
	 */
	public static MethodExpressionActionListener createMethodExpressionActionListener(
			FacesContext context, String expression) {
		return new MethodExpressionActionListener(context.getApplication()
				.getExpressionFactory().createMethodExpression(
						context.getELContext(), expression, Void.class,
						new Class[] { ActionEvent.class }));
	}

	/**
	 * 获取绝对物理路径
	 * 
	 * @param path
	 *            相对路径
	 * @return 对应的绝对物理路径字符串
	 */
	public static String getRealPath(String path) {
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext eContext = context.getExternalContext();
		ServletContext sContext = (ServletContext) eContext.getContext();
		return sContext.getRealPath(path);
	}

	/**
	 * 获取网站的BasePath
	 * 
	 * @return 网站的BasePath的字符串
	 */
	public static String getBasePath() {
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext eContext = context.getExternalContext();
		ServletRequest req = (ServletRequest) eContext.getRequest();
		return (req.getScheme() + "://" + req.getServerName() + ":"
				+ req.getServerPort() + eContext.getRequestContextPath() + "/");
	}
}
